package cn.hchaojie.blog.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.hchaojie.blog.domain.AjaxResponse;
import cn.hchaojie.blog.domain.Post;

public class BaseServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 根据请求路径，调用对应的方法
		// 一：获取请求路径，截取最后一部分，得到一个方法名
		// /category/findAll
		String uri = req.getRequestURI();
		int index = uri.lastIndexOf('/');
		String methodName = uri.substring(index + 1);

		// 二：根据方法名称，调用servlet里面对应的方法
		try {
			Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, req, resp); // this.findAll(req, resp);
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	
	public <E> void writePageData(HttpServletResponse resp, AjaxResponse<E> result) throws IOException {
		String string = JSON.toJSONString(result);
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write(string);	
	}
	
	// 方法上面的泛型
	public <E> void writeListData(HttpServletResponse resp, List<E> data) throws IOException {
		AjaxResponse<E> reponse = new AjaxResponse<>();
		reponse.setCode(0);
		reponse.setCount(100);	// 数据库一共多少条记录，（分页用）
		reponse.setMsg("success");
		reponse.setData(data);
		
		String string = JSON.toJSONString(reponse);
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write(string);	
	}
	
	public void writeSimpleData(HttpServletResponse resp) throws IOException {
		AjaxResponse reponse = new AjaxResponse();
		reponse.setCode(0);
		reponse.setMsg("");
		
		String string = JSON.toJSONString(reponse);
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write(string);	
	}
}
